import sys
import json
import os
import logging
import sys
from mgamedev.py_lib.remote import RemoteCtrl  # noa


def update_git(rctl, path_ding):
    cmd_reback = "cd %s && git checkout -- ./" % path_ding
    print("revert git--->>\n%s" % rctl.ssh_command(cmd_reback))
    cmd_str = "cd %s && git pull" % path_ding
    print("update git--->>\n%s" % rctl.ssh_command(cmd_str))


def killall_openresty(rctl, path_ding):
    cmd_str = "cd %s/operation_tool && python stop.py" % path_ding
    print("killall openresty --->>\n%s" % rctl.ssh_command(cmd_str))


def start_openresty(rctl, path_ding, conff="nginx_release.conf"):
    cmd_str = "cd %s/operation_tool && python start.py %s" % (path_ding, conff)
    print("start openresty --->>\n%s" % rctl.ssh_command(cmd_str))


class CtlRemote:

    CONF_FILE = os.path.join(os.path.dirname(__file__), "data.d")

    def get_conf(self, skey):
        dic_conf = json.loads(open(self.CONF_FILE, "r").read())
        if skey not in dic_conf:
            print("no config for the key<%s>!\n" % skey)
            print("make the key belong them:<%s>", dic_conf.keys())
            sys.exit()
        return dic_conf[skey]

    def execute_rel(self, skey, conff):
        dic_conf = self.get_conf(skey)
        IP, UNAME, PWD, GIT_PATH, PORT = dic_conf["IP"], dic_conf[
            "UNAME"], dic_conf["PWD"], dic_conf["GIT_PATH"], dic_conf["PORT"]
        cli = RemoteCtrl(IP, PORT, UNAME, PWD)

        update_git(cli, GIT_PATH)
        killall_openresty(cli, GIT_PATH)
        start_openresty(cli, GIT_PATH, conff)

        cli.close()
